@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: PPH系统生产环境部署脚本 - 方案1：CMD命令部署
:: 支持服务器断电重启、崩溃重启、错误重启

echo ========================================
echo PPH Production Deployment - CMD Method
echo ========================================
echo.

:: 设置部署目录
set "DEPLOY_DIR=%~dp0.."
set "APP_DIR=%DEPLOY_DIR%\app"
set "LOG_DIR=%APP_DIR%\logs"
set "BACKUP_DIR=D:\PPH-Backups"

echo [INFO] Deployment directory: %DEPLOY_DIR%
echo [INFO] Application directory: %APP_DIR%
echo.

:: 第1步：环境检查
echo [STEP 1] Environment Check
echo ========================================

:: 检查管理员权限
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Administrator privileges required
    echo Please run this script as Administrator
    pause
    exit /b 1
)
echo [OK] Administrator privileges confirmed

:: 检查Node.js（严格检查18.17.1）
node --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Node.js not found
    echo Please install Node.js 18.17.1 from:
    echo https://nodejs.org/dist/v18.17.1/node-v18.17.1-x64.msi
    pause
    exit /b 1
)

for /f "tokens=*" %%i in ('node --version') do set NODE_VERSION=%%i
echo Current Node.js version: %NODE_VERSION%

:: 严格检查版本必须为18.17.1
echo %NODE_VERSION% | findstr "v18\.17\.1" >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Node.js 18.17.1 is required!
    echo Current version: %NODE_VERSION%
    echo.
    echo ❌ Forbidden versions: 22.x, 20.x, 19.x (will cause system failure)
    echo ✅ Required version: 18.17.1 (exact version)
    echo.
    echo Please install the correct version:
    echo   1. Download: https://nodejs.org/dist/v18.17.1/node-v18.17.1-x64.msi
    echo   2. Or use nvm: nvm install 18.17.1 && nvm use 18.17.1
    echo.
    pause
    exit /b 1
)
echo [OK] Node.js 18.17.1 confirmed - correct version!

:: 检查npm
npm --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] npm not found
    pause
    exit /b 1
)

for /f "tokens=*" %%i in ('npm --version') do set NPM_VERSION=%%i
echo [OK] npm version: %NPM_VERSION%
echo.

:: 第2步：停止现有服务
echo [STEP 2] Stop Existing Services
echo ========================================

:: 检查PM2是否已安装
pm2 --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [INFO] PM2 not installed, will install later
) else (
    echo [INFO] Stopping existing PM2 services...
    pm2 stop all >nul 2>&1
    pm2 delete all >nul 2>&1
    pm2 kill >nul 2>&1
    echo [OK] Existing services stopped
)

:: 清理端口占用
echo [INFO] Cleaning port conflicts...
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3010') do taskkill /f /pid %%a >nul 2>&1
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3011') do taskkill /f /pid %%a >nul 2>&1
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3012') do taskkill /f /pid %%a >nul 2>&1
echo [OK] Port conflicts cleared
echo.

:: 第3步：创建目录结构
echo [STEP 3] Create Directory Structure
echo ========================================

if not exist "%APP_DIR%" mkdir "%APP_DIR%"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"
if not exist "%BACKUP_DIR%" mkdir "%BACKUP_DIR%"

echo [OK] Directory structure created
echo.

:: 第4步：安装PM2
echo [STEP 4] Install PM2 Process Manager
echo ========================================

pm2 --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [INFO] Installing PM2...
    npm install -g pm2
    if %errorlevel% neq 0 (
        echo [ERROR] PM2 installation failed
        pause
        exit /b 1
    )
    echo [OK] PM2 installed successfully
) else (
    echo [OK] PM2 already installed
)

:: 验证PM2安装
for /f "tokens=*" %%i in ('pm2 --version') do set PM2_VERSION=%%i
echo [OK] PM2 version: %PM2_VERSION%
echo.

:: 第5步：安装项目依赖
echo [STEP 5] Install Dependencies
echo ========================================

cd /d "%DEPLOY_DIR%"

:: 安装根目录依赖
if exist "package.json" (
    echo [INFO] Installing root dependencies...
    npm install --production
    if %errorlevel% neq 0 (
        echo [ERROR] Root dependencies installation failed
        pause
        exit /b 1
    )
    echo [OK] Root dependencies installed
)

:: 安装后端依赖
if exist "%APP_DIR%\backend\package.json" (
    echo [INFO] Installing backend dependencies...
    cd /d "%APP_DIR%\backend"
    npm install --production
    if %errorlevel% neq 0 (
        echo [ERROR] Backend dependencies installation failed
        pause
        exit /b 1
    )
    echo [OK] Backend dependencies installed
)

:: 安装前端依赖并构建
if exist "%APP_DIR%\frontend\package.json" (
    echo [INFO] Installing frontend dependencies...
    cd /d "%APP_DIR%\frontend"
    npm install
    if %errorlevel% neq 0 (
        echo [ERROR] Frontend dependencies installation failed
        pause
        exit /b 1
    )
    echo [OK] Frontend dependencies installed
    
    echo [INFO] Building frontend...
    npm run build
    if %errorlevel% neq 0 (
        echo [ERROR] Frontend build failed
        pause
        exit /b 1
    )
    echo [OK] Frontend built successfully
)

cd /d "%DEPLOY_DIR%"
echo.

:: 第6步：配置防火墙
echo [STEP 6] Configure Windows Firewall
echo ========================================

echo [INFO] Configuring firewall rules...
netsh advfirewall firewall delete rule name="PPH-Frontend-3010" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-Backend-3011" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-Management-3012" >nul 2>&1

netsh advfirewall firewall add rule name="PPH-Frontend-3010" dir=in action=allow protocol=TCP localport=3010
netsh advfirewall firewall add rule name="PPH-Backend-3011" dir=in action=allow protocol=TCP localport=3011
netsh advfirewall firewall add rule name="PPH-Management-3012" dir=in action=allow protocol=TCP localport=3012

echo [OK] Firewall rules configured
echo.

:: 第7步：启动服务
echo [STEP 7] Start Services
echo ========================================

echo [INFO] Starting PPH services with PM2...
cd /d "%DEPLOY_DIR%"

:: 设置环境变量
set NODE_PATH=%CD%\node_modules
set PATH=%NODE_PATH%\.bin;%PATH%

:: 启动服务
pm2 start config\ecosystem.config.cjs --env production
if %errorlevel% neq 0 (
    echo [ERROR] Service startup failed
    echo Check logs: pm2 logs
    pause
    exit /b 1
)

:: 保存PM2配置
pm2 save
echo [OK] Services started and configuration saved
echo.

:: 第8步：设置开机自启动
echo [STEP 8] Configure Auto-startup
echo ========================================

echo [INFO] Configuring auto-startup...
pm2 startup windows >nul 2>&1
if %errorlevel% neq 0 (
    echo [WARNING] Auto-startup configuration may have failed
    echo You may need to configure manually
) else (
    echo [OK] Auto-startup configured
)
echo.

:: 第9步：验证部署
echo [STEP 9] Verify Deployment
echo ========================================

echo [INFO] Waiting for services to start...
timeout /t 10 /nobreak >nul

:: 检查PM2状态
echo [INFO] Checking PM2 status...
pm2 list

:: 检查端口监听
echo [INFO] Checking port status...
netstat -an | findstr :3010 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Frontend port 3010 is listening
) else (
    echo [WARNING] Frontend port 3010 not listening
)

netstat -an | findstr :3011 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Backend port 3011 is listening
) else (
    echo [WARNING] Backend port 3011 not listening
)

netstat -an | findstr :3012 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Management port 3012 is listening
) else (
    echo [WARNING] Management port 3012 not listening
)

:: 健康检查
echo [INFO] Performing health check...
curl -s http://localhost:3011/api/health >nul 2>&1
if %errorlevel% equ 0 (
    echo [OK] Backend health check passed
) else (
    echo [WARNING] Backend health check failed
)
echo.

:: 部署完成
echo ========================================
echo DEPLOYMENT COMPLETED SUCCESSFULLY!
echo ========================================
echo.
echo Access URLs:
echo - Frontend: http://localhost:3010
echo - Backend API: http://localhost:3011/api
echo - Management: http://localhost:3012
echo.
echo Management Commands:
echo - Check status: pm2 list
echo - View logs: pm2 logs
echo - Restart all: pm2 restart all
echo - Stop all: pm2 stop all
echo.
echo Log files location: %LOG_DIR%
echo Backup directory: %BACKUP_DIR%
echo.

pause
